package com.zuikaku.nettychat.utils;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtobufIOUtil;
import com.dyuproject.protostuff.Schema;
import com.zuikaku.nettychat.netty.dto.NettyResponse;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

public class ConvertTools {

    private static int bytesToInt(byte[] data){
        int num=0;
        for(int i=0;i<4;i++){
            num<<=8;
            num|=(data[i]&0xff);
        }
        return num;

    }

    private static byte[] intToBytes(int num){
        byte[] b = new byte[4];
        for(int i=0;i<4;i++){
            b[i]=(byte)(num>>>(24-i*8));
        }
        return b;
    }

    public static byte[] byteBuffToBytes(Object msg){
        if(!(msg instanceof ByteBuf)){
            return null;
        }
        ByteBuf byteBuf = (ByteBuf)msg;
        //先判断长度是否小于4
        if(byteBuf.readableBytes()<4){
            return null;
        }
        byteBuf.markReaderIndex();
        byte[] lenBytes = new byte[4];
        //获得消息体长度
        byteBuf.readBytes(lenBytes);
        int length = bytesToInt(lenBytes);
        //判断消息体长度是否接收够
        if(byteBuf.readableBytes()<length){
            byteBuf.resetReaderIndex();
            return null;
        }
        //解析为消息体
        byte[] dataBytes = new byte[length];
        byteBuf.readBytes(dataBytes);
        return dataBytes;
    }

    public static ByteBuf nettyResponseToByteBuff(NettyResponse nettyResponse, Schema schema){
        LinkedBuffer buffer =LinkedBuffer.allocate(1024);
        byte[] msgData = ProtobufIOUtil.toByteArray(nettyResponse,schema,buffer);
        ByteBuf byteBuf = Unpooled.copiedBuffer(intToBytes(msgData.length),msgData);
        return byteBuf;
    }
}
